<?php

namespace frontend\controllers;

use common\models\AddressCity;
use common\models\AddressDistrict;
use common\models\CepingReport;
use common\models\CepingResult;
use common\models\Img;
use common\models\User;
use Yii;
use common\models\UserMess;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * UsermessController implements the CRUD actions for UserMess model.
 */
class UsermessController extends Controller
{
    public $layout='meno.php';
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all UserMess models.
     * @return mixed
     */
    public function actionIndex()
    {
        $this->layout='ucenter.php';
        return $this->render('index');
    }

    /**
     * Displays a single UserMess model.
     * @param string $id
     * @return mixed
     */
    public function actionView($uid)
    {
        return $this->render('view', [
            'model' => $this->findModel($uid),
        ]);
    }

    /**
     * Creates a new UserMess model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new UserMess();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing UserMess model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate_a()
    {
        $uid=Yii::$app->user->id;
        $model = UserMess::find()->where(['id'=>$uid])->one();
      //  p($model);die;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['update_b','uid'=>$uid]);
        }
        else  return $this->render('update_a', ['model' => $model,]);
    }

    public function actionUpdate_b(){
        $uid=Yii::$app->user->id;
        $model = UserMess::find()->where(['id'=>$uid])->one();
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                //如果是第一次补充资料
                return $this->redirect(['grouth/index']);
            } else   return $this->render('update_b', ['model' => $model,]);

    }

    public function actionUpdate_self($uid)
    {
        //   p($uid);die;
        $model = $this->findModel($uid);

            //  p(Yii::$app->request->post());die;
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                if(!empty($model->username)){
                    $user=User::find()->where(['id'=>Yii::$app->user->id])->one();
                    $user->username=$model->username;
                    $user->save();
                }
                    return $this->redirect(['usercenter/index']);

            } else {
                return $this->render('update_self', [
                    'model' => $model,
                ]);
            }
    }


    /**
     * Deletes an existing UserMess model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($uid)
    {
        $this->findModel($uid)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the UserMess model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return UserMess the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($uid)
    {
        if (($model = UserMess::find()->where(['uid'=>$uid])->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionListcity($proid){

        $countBranches = AddressCity::find()
            ->where(['provinceCode' => $proid])
            ->count();
        $branches = AddressCity::find()
            ->where(['provinceCode' => $proid])
            ->all();
        if ($countBranches > 0) {
            echo "<option>全部</option>";
            foreach ($branches as $branche) {
                echo "<option value='" . $branche->code . "'>" . $branche->name . "</option>";
            }
        } else {
            echo "<option>全部</option>";
        }
    }
    public function actionListdistrict($cityid){

        $countBranches = AddressDistrict::find()
            ->where(['cityCode' => $cityid])
            ->count();
        $branches = AddressDistrict::find()
            ->where(['cityCode' => $cityid])
            ->all();
        if ($countBranches > 0) {
            foreach ($branches as $branche) {
                echo "<option value='" . $branche->code . "'>" . $branche->name . "</option>";
            }
        } else {
            echo "<option>-</option>";
        }
    }

    public function actionUpload()
    {
        if (isset($_POST['timestamp'])) {
//          return json_encode("没有上传文件");
                $targetFolder = Yii::$app->basePath.'/web/uploads/touxiang/' . date('Ymd');
                $cate='pic';

            if(!file_exists($targetFolder)) {
                $dir=$targetFolder;  $mode=0777;
                mkdir($dir, $mode);
            }
            if (!empty($_FILES)) {
//              p($_FILES);die;
                $tempFile = $_FILES['UserMess']['tmp_name'][$cate];
                $fileParts = pathinfo($_FILES['UserMess']['name'][$cate]);
                $extension = $fileParts['extension'];
                $random = time() . rand(1000, 9999);
                $randName = $random . "." . $extension;
                $targetFile = rtrim($targetFolder, '/') . '/' . $randName;
                $fileTypes = array('jpg', 'jpeg', 'gif', 'png');

                $uploadfile_path = '/uploads/touxiang/' . date('Ymd') . '/' . $randName;
                $uploadfile_path_small = '/uploads/touxiang/' . date('Ymd') . '/small' . $randName;

                $callback['url'] = $uploadfile_path;
                $callback['url_small'] = $uploadfile_path_small;
                $callback['filename'] = $fileParts['filename'];
                $callback['randName'] = $random;
                if (in_array($fileParts['extension'], $fileTypes)) {
                    move_uploaded_file($tempFile, $targetFile);
//              p(111111);die;
                        self::Savepic($callback['url'],$callback['url_small'],Yii::$app->user->id); //更新数据库中img_samll字段

                         return json_encode("上传成功");
                } else {
                    return json_encode('不能上传后缀为' . $fileParts['extension'] . '文件');
                }
            } else {
                return json_encode("没有上传文件");
            }
        }
        else   return json_encode("没有上传文件");

    }
    public function Savepic($url,$url_small,$id)
    {


        if(\yii\imagine\Image::thumbnail(Yii::$app->basePath.'/web'.$url, 230, 230)
            ->save(Yii::$app->basePath.'/web'.$url_small, ['quality' => 100])){

            if($img=Img::findOne($id)){
                $img->img_big=$url;
                $img->img_small=$url;
                $img->save();
                return true;
           }
            else{
                $img=new Img;
                $img->id=$id;
                $img->uid=$id;
                $img->type=1;
                $img->type_id=1;
                $img->img_big=$url;
                $img->img_small=$url;
                $img->save();
                return true;
            }
        }
        else    return false;

    }


}
